package app.contatos;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import app.contatos.model.ContatoHelper;
import app.contatos.view.SalvarActivity;

public class MainActivity extends Activity {
	
	ContatoHelper helper = null;
	private Cursor model = null;
	private ContatoAdapter adapter = null;
	private ListView listView = null;
	public static final String _ID = "app.contatos._ID"; 
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        helper = new ContatoHelper(this);
        carregar();
        configurar();
    }
    
    private void configurar() {
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				irParaSalvar(String.valueOf(id));
			}
		});
		
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					final int position, final long id) {
				final String[] itens = {"Editar", "Deletar", "Chamar", "Enviar e-mail"};
				AlertDialog.Builder dialogo = new AlertDialog.Builder(MainActivity.this);
				dialogo.setTitle("Opções");
				dialogo.setItems(itens, new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0: // editar
							irParaSalvar(String.valueOf(id));
							break;
						case 1: // deletar
							AlertDialog.Builder confirmacao = new AlertDialog.Builder(MainActivity.this);
							confirmacao.setTitle("Deletar");
							confirmacao.setMessage("Deseja realmente deletar este contato?");
							confirmacao.setPositiveButton("Sim", new OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									int linhasAfetadas = helper.deletar(String.valueOf(id));
									if (linhasAfetadas > 0) {
										exibirMensagem("Contatos deletado com sucesso");
										carregar();
									} else {
										exibirMensagem("Falha ao deletar contato :(");
									}
								}
							});
							confirmacao.setNegativeButton("Não", null);
							confirmacao.show();
							break;
						case 2: // chamar
							model.moveToPosition(position);
							startActivity(new Intent(Intent.ACTION_CALL,
											Uri.parse("tel:" + helper.getTelefone(model))
										 )
							);
							break;
						case 3: // enviar e-mail
							model.moveToPosition(position);
							Intent email = new Intent(Intent.ACTION_SEND);
							email.setType("plain/text");
							email.putExtra(Intent.EXTRA_EMAIL, new String[]{ helper.getEmail(model) });
							startActivity(Intent.createChooser(email, "Enviar e-mail..."));
							break;
						}
					}
				});
				dialogo.show();
				return true;
			}
		});
	}
    
    public void exibirMensagem(String mensagem) {
    	Toast.makeText(this, mensagem, Toast.LENGTH_LONG).show();
    }

	public void carregar() {
    	listView = (ListView) findViewById(R.id.contatos);
    	model = helper.listar();
    	startManagingCursor(model);
    	adapter = new ContatoAdapter(model);
    	listView.setAdapter(adapter);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	new MenuInflater(this).inflate(R.menu.main_menu, menu);
    	return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	if (item.getItemId() == R.id.menuAdd) {
			irParaSalvar();
			return true;
		}
    	return super.onOptionsItemSelected(item);
    }
    
    public void irParaSalvar() {
		irParaSalvar(null);
	}

	public void irParaSalvar(String id) {
    	Intent intent = new Intent(MainActivity.this, SalvarActivity.class);
    	if (id != null) {
    		intent.putExtra(_ID, id);
    	}
    	startActivity(intent);
    }
    
    private static class ContatoHolder {
    	private TextView nome, telefone, email = null;
    	//private ImageView icone = null;
    	
    	public ContatoHolder(View linha) {
    		nome = (TextView) linha.findViewById(R.id.linha_nome);
    		telefone = (TextView) linha.findViewById(R.id.linha_telefone);
    		email = (TextView) linha.findViewById(R.id.linha_email);
    		//icone = (ImageView) linha.findViewById(R.id.linha_icone);
    	}
    	
    	public void popularLinha(Cursor c, ContatoHelper helper) {
    		nome.setText(helper.getNome(c));
    		telefone.setText(helper.getTelefone(c));
    		email.setText(helper.getEmail(c));
    	}
    }
    
	private class ContatoAdapter extends CursorAdapter {

		public ContatoAdapter(Cursor c) {
			super(MainActivity.this, c);
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			ContatoHolder holder = (ContatoHolder) view.getTag();
			holder.popularLinha(cursor, helper);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater inflater = getLayoutInflater();
			View linha = inflater.inflate(R.layout.linha, parent, false);
			ContatoHolder holder = new ContatoHolder(linha);
			linha.setTag(holder);
			return linha;
		}
    	
    }
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		helper.close();
	}
}